module pet {
	export class NetMgr {
		public constructor() {
		}
		//---------------------------------WebSocket------------------------------------//
		private socket:egret.WebSocket;
		public initSocket(host:string, port:number){
			if( !this.socket){
				this.socket = new egret.WebSocket();
				this.socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onData, this);
				this.socket.addEventListener(egret.Event.CONNECT, this.onConnect, this);
				this.socket.addEventListener(egret.Event.CLOSE, this.onClose, this);
				this.socket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onIOError, this);
			}
			if( this.socket.connected){
				this.socket.close();
			}
			this.socket.connect(host, port);
		}

		private onData(e:egret.ProgressEvent){
			let result = this.socket.readUTF();
			egret.log('[RECV]:',result);
			let data = JSON.parse(result);
		}
		private onConnect(e:egret.Event){
			egret.log('[LOG]:Socket connected');
			this.sendWS(CmdMgr.Login,{account:'111111'})
		}
		private onClose(e:egret.Event){
			egret.log('[LOG]:Socket Closed');
		}
		private onIOError(e:egret.IOErrorEvent){
			egret.error(e);
		}
		//------------------------------------HTTP---------------------------------------//
		public sendWS(proto:number, data:any=null){
			if( !this.socket.connected){
				egret.error('Socket closed.');
				return;
			}
			let req:Req = Req.getReq();
			req.pid = proto;
			if( data ){
				req.data = data;
			}
			this.socket.writeUTF(JSON.stringify(req));
		}
		public sendHttp(url:string, method=egret.URLRequestMethod.GET,callBack:Function, callObj:any){
			let request:egret.HttpRequest = new egret.HttpRequest();
			request.open(url,method);
			request.send();
			request.addEventListener(egret.Event.COMPLETE, (e)=>{
				callBack.call(callObj,request.response)
			},null);
			request.addEventListener(egret.IOErrorEvent.IO_ERROR, (e)=>{

			},null);
			request.addEventListener(egret.ProgressEvent.PROGRESS, (e)=>{

			},null);
		}
		private static _instance:NetMgr;
		public static get Instance(){
			if( !NetMgr._instance ) NetMgr._instance = new NetMgr();
			return NetMgr._instance;
		}
	}
}